//
//  DataFilter.m
//  Fantasia
//
//  Created by kongkong on 2016/12/24.
//  Copyright © 2016年 Kongkong. All rights reserved.
//

#import "DataFilter.h"

const NSString *tailKey = @"__fan_tail__";
const NSString *hiddenKey = @"__fan_hidden__";
const NSString *boolLogoKey = @"__fan_logo__";

@implementation DataFilter

static NSDictionary *filterMap;

+ (NSDictionary *)filterMapWithGroup:(FilterGroup)group {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSData* filterJson = [NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"filter" ofType:@"json"]];
        
        filterMap = [NSJSONSerialization JSONObjectWithData:filterJson options:NSJSONReadingMutableContainers error:nil];
    });

    return filterMap[[NSString stringWithFormat:@"%d",group]];
}

+ (NSArray *)filterData:(NSMutableDictionary *)data withGroup:(FilterGroup)group {
    NSDictionary *filterMap = [DataFilter filterMapWithGroup:group];
    NSMutableArray *hiddenKeys = [NSMutableArray array];

    [data enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL *_Nonnull stop) {
        data[key] = [[DataModel alloc] init];
        NSDictionary *valueFilter = filterMap[key];
        NSString *hiddenValue = valueFilter[hiddenKey];
        if ([hiddenValue isEqualToString:obj]) {
            [hiddenKeys addObject:key];
        } else {
            NSString *stringValue = [DataFilter filterDataWithValueFilter:valueFilter originData:obj];
            ((DataModel *) data[key]).title = key;

            if ([stringValue hasPrefix:[boolLogoKey copy]]) {
                ((DataModel *) data[key]).boolLogoColor = [UIColor colorWithHexString:[stringValue substringFromIndex:boolLogoKey.length]];
                ((DataModel *) data[key]).type = DataType_BoolLogo;
            } else {
                ((DataModel *) data[key]).textValue = stringValue;
            }
        }

    }];

    return (hiddenKeys.count == 0) ? nil : [hiddenKeys copy];
}

+ (NSString *)filterDataWithValueFilter:(NSDictionary *)valueFilter originData:(NSString *)originData {
    if (!valueFilter) {
        return originData;
    }
    NSString *ret = originData;

    if ([valueFilter[boolLogoKey] isKindOfClass:[NSDictionary class]]) {
        if (EMPTY_STR(originData)) {
            originData = @"0";
        }
        ret = [boolLogoKey stringByAppendingString:valueFilter[boolLogoKey][originData]];
    } else {
        ret = valueFilter[originData];

        NSString *tail = valueFilter[tailKey];
        if (tail) {
            ret = [ret stringByAppendingFormat:@" %@", tail];
        }
    }


    return ret;
}
@end
